//
//  XS_CertUploadVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/11.
//

import UIKit

class XS_CertUploadVC: XS_BaseVC {
    
    @IBOutlet weak var whiteBgV: UIView!
    @IBOutlet weak var grayBgV: UIView!

    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var timeTextField: UITextField!
    @IBOutlet weak var levelTextField: UITextField!
    
    @IBOutlet weak var uploadImageBtn: QMUIButton!
    var certPicUrl : String?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "证书上传"
        shouldNavBarHidden = true
        isStatusBarBlack = false
        loadCustomBar()
        uploadImageBtn.imagePosition = .top
        uploadImageBtn.spacingBetweenImageAndTitle = 8
        
        whiteBgV.layer.masksToBounds = true
        whiteBgV.layer.cornerRadius = .scale * 4
        grayBgV.layer.masksToBounds = true
        grayBgV.layer.cornerRadius = .scale * 4
        grayBgV.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
    }

    @IBAction func selectImageBtnAction(_ sender: QMUIButton) {
        let picker = TZImagePickerController.init(maxImagesCount: 1, delegate: nil)
        picker?.allowTakeVideo = false
        picker?.allowPickingVideo = false
        picker?.didFinishPickingPhotosHandle = {(photos, assets, isSelectOriginPhoto) in
            if let data = photos?.first?.jpegData(compressionQuality: 0.1) {
                XS_NetWork.xs_uploadFile(XS_NetWork.XS_UploadM(data: data)) { resp in
                    self.certPicUrl = resp?.data ?? ""
                }
            }
            sender.setBackgroundImage(photos?.first, for: .normal)
            sender.setTitle("", for: .normal)
        }
        picker?.modalPresentationStyle = .fullScreen
        present(picker!, animated: true, completion: nil)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        view.endEditing(true)
    }
    
    @IBAction func selectTimeBtnAction(_ sender: Any) {
        view.endEditing(true)
        BRDatePickerView.showDatePicker(with: .YMD, title: "请选择获得时间", selectValue: nil, minDate: nil, maxDate: Date.init(), isAutoSelect: false) { (date, stringDate) in
            let dateF = DateFormatter()
            dateF.dateFormat = "yyyy年MM月dd日"
            self.timeTextField.text = dateF.string(from: date!)
            self.levelTextField.becomeFirstResponder()
        }
    }
    
    @IBAction func uploadBtnAction(_ sender: UIButton) {
        if certPicUrl?.count ?? 0 > 0 {
            if checkTextField(textField: nameTextField) {
                if checkTextField(textField: timeTextField) {
                    if checkTextField(textField: levelTextField) {
                        XS_NetWork.requestJson("/userCertification/insert", parameters: ["certificateImgSrc":certPicUrl ?? "","certificationName":nameTextField.text ?? "","getTime":timeTextField.text ?? "","level":levelTextField.text ?? ""])
                        .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                            self.view.makeToast(resp.msg)
                            self.navigationController?.popViewController(animated: true)
                        }).disposed(by: disposeBag)
                    }
                }
            }
        }else{
            view.makeToast("未上传证书照片")
        }
    }
    
    func checkTextField(textField : UITextField) -> Bool{
        let text = textField.text
        let newText = text?.replacingOccurrences(of: " ", with: "")
        if newText?.count ?? 0 > 0 {
            return true
        }
        if nameTextField == textField {
            view.makeToast("未输入证书名称")
        }else if timeTextField == textField {
            view.makeToast("未输入获得时间")
        }else if levelTextField == textField {
            view.makeToast("未输入证书级别")
        }
        return false
    }
}

extension XS_CertUploadVC : UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if nameTextField == textField {
            nameTextField.resignFirstResponder()
            selectTimeBtnAction(UIButton())
        }else if timeTextField == textField {
            levelTextField.becomeFirstResponder()
        }else if levelTextField == textField {
            view.endEditing(true)
        }
        return true
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == levelTextField {
            UIView.animate(withDuration: 0.2) {
                self.view.transform = CGAffineTransform(translationX: 0, y: -.scale * 80)
            }
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == levelTextField {
            UIView.animate(withDuration: 0.2) {
                self.view.transform = .identity
            }
        }
    }
}
